<template>
	<div id="home">
		<div v-if="!active"  id="banke">
			<van-nav-bar title="班课" fixed @click-right="onClickRight" :right-text="bankeMsg">
				<template #left v-if="userInfo.roles[0] === 'STUDENT'" >
					<van-icon name="scan" size="28px" v-auth="['scan']" @click="$router.push({
						name: 'QR',
						// params: {
						// 	bkInfo: c
						// }
					})"/>
				</template>
			</van-nav-bar>

			<van-dialog
				v-model="showDiolog"
				show-cancel-button
				:beforeClose="beforeClose"
			>
				<van-field
					v-model="bankeId"
					label="班课号"
					placeholder="请输入班课号"
					type="digit"
				/>				
			</van-dialog>

			
			<van-pull-refresh v-if="courseInfo.total" v-model="refreshing" @refresh="onRefresh">
				<van-list 
					v-model="loading"
					:finished="finished"
					finished-text="------已经到底啦------"
					@load="onLoad"
				>
					<div>						
						<van-cell-group title="">
							<van-cell v-for="(c,index) in courseInfo.records" :title="c.name" :key="index" 
									value="" :label="c.title" icon="photo-fail" center is-link @click="goDetailBanke(c)"/>
							<!-- <van-cell title="工程实践" value="" label="池芝标" icon="photo-fail" is-link center @click="goDetailBanke"/> -->
						</van-cell-group>						
					</div>
				</van-list>
			</van-pull-refresh>
			<van-empty v-else description="貌似没有数据哦">
				<van-button round type="danger" class="bottom-button" @click="onRefresh">点击刷新</van-button>
			</van-empty>
		</div>
		<!-- <banke v-if="!active" :course.sync="courseInfo" :user="userInfo"></banke> -->
		<me v-else ></me>
		<div>
			<van-tabbar v-model="active">
				<van-tabbar-item icon="home-o"  >班课</van-tabbar-item>
				<van-tabbar-item icon="friends-o" dot>我的</van-tabbar-item>
			</van-tabbar>
		</div>


	</div>
</template>

<script>
	
	import me from '@/components/home/me.vue';
	import { Toast } from 'vant';
	import { pageCourseForTeacher, pageCourseForStudent, getCourse} from '@/api/course.js';
	//import { Dialog } from 'vant';
	import {joinCourse, ifJoinCourse} from '@/api/member.js'
	export default {
		name: 'home',
		components: {
			me
		},
		created() {
			this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
			if(this.$route.params.active)
				this.active = this.$route.params.active;
		},
		computed: {
			bankeMsg() {
				return this.userInfo.roles[0] === 'TEACHER'?'创建新班课':'加入班课';
			},
		},
		data() {
			return {				
				active: 0, // tab
				courseInfo: {
					records:[],
					total:1,
				},
				userInfo: {},

				
				maxPage: 6,
				currentPage: 1,

				refreshing: false, // 下拉刷新用
				loading: false, // 下面的那个加载中显示 v-model
				finished: false,  //  数据全部加载完成否？

				showDiolog: false, // 展示加入班课的diolog
				bankeId: '',  // 输入的要加入的班课的id号
			};
		},
		methods: {
			async onRefresh() {   // 下拉刷新
				console.log('onRefresh');	
				
				this.currentPage = 1;
				this.courseInfo.records = [];
				this.finished = false;

				this.loading = true;
				setTimeout(() => {
					Toast('刷新成功');
					this.onLoad();
					this.refreshing = false;
				}, 1000);
					
				

			},
			onClickRight() { // 点击顶部右侧
				if (this.userInfo.roles[0] === 'TEACHER') { // teacher
					this.$router.push('/home/newBanke');
				} else if(this.userInfo.roles[0] === 'STUDENT') { // student 
					this.showDiolog = !this.showDiolog;
					// Dialog.confirm({
					// 	title: '加入班课',
					// 	message: '弹窗内容',
					// 	theme: 'round-button',
					// }).then(() => {
					// // on confirm
					// }).catch(() => {
					// 	// on cancel
					// });
				}
			},
			async beforeClose(action, done) {  // 加入班课Diolog的回调函数
				let stateCode = 0; // 三种状态的判断 1：已加入班课、2：班课不存在、3：班课未开放、4：课程已结束、5：课程可以加入
				let openState = false;
				let endState = false;
				let joinState = false;
				if(action === 'confirm' && this.bankeId !== '') {  // 不空
					
					await getCourse(this.bankeId).then(res => { // 看班课信息
						console.log(res)
						if(res.data.code === 0) { 
							console.log('班课存在');
							openState = res.data.data.opened;
							endState = res.data.data.ended;
							stateCode++; // 1 班课存在
						} else if(res.data.code === 1008) {   
							Toast('班课不存在');
							done() //关闭
						} else {
							Toast(res.data.msg);
						}
					}).catch(err => {
						console.log(err);
						Toast('请求失败或超时');
					});
					if(stateCode === 1) {
						await ifJoinCourse(this.bankeId).then(res => { // 是否加入班课
							console.log(res)
							if(res.data.code === 0) {
								joinState = res.data.data;
								if(joinState) {
									Toast('已经加入班课');
									done() //关闭									
								} else {
									console.log('没有加入班课');
									stateCode++; // 2 班课存在且没有加入班课
								}
							} else {  
								Toast(res.data.msg);							
							}
						}).catch(err => {
							console.log(err);
							Toast('请求失败或超时');
						});
					}
					
					if(stateCode === 2 ) { // 2 班课存在且没有加入班课
						if(endState) { // 课程结束了
							Toast('该班课已结束');
							done() //关闭
						} else {
							stateCode++; // 3 班课存在且没有加入班课 且 课程没有结束
						}
					}

					if(stateCode === 3 ) { // 3 班课存在且没有加入班课 且 课程没有结束
						if(openState) { // 课程开放
							await joinCourse(this.bankeId).then(res => {
								console.log(res)
								if(res.data.code === 0) {
									Toast('加入班课成功');
									this.onRefresh();
								} else if(res.data.code === 1005) {  
									Toast('加入班课失败');
								}
							}).catch(err => {
								console.log(err);
								Toast('请求失败或超时');
							});
							this.bankeId = '';
							done();
						} else {
							Toast('该班课不允许加入');
							stateCode++; // 4 班课存在且没有加入班课 且 课程没有结束   但不允许加入
						}
					} 
					if(stateCode > 3) { 				
						done() //关闭											
					}
					
				} else if(action === 'cancel') {
					done() //关闭
				}

				this.bankeId = '';

			},
			onLoad() { 
				
				console.log('onLoad')
				this.getList();
				this.currentPage++;
				console.log('+++++++++++' + this.currentPage);

				// setTimeout(() => {
				// 	// 服务器请求任务
				// 	Toast('加载成功');
				// 	this.refreshing = false;
				// }, 1000);
			},
			async getList() { //  获取班课列表信息
				if(this.userInfo.roles[0] === 'TEACHER') {  // 教师
					await pageCourseForTeacher(this.currentPage , this.maxPage).then(res => {
						console.log(res.data.data);
						if (res.data.data.records.length === 0) { // 判断获取数据条数若等于0
							this.finished = true; // 停止加载
							console.log('停止加载');
						} else {
							this.courseInfo.total = res.data.data.total; // 给数据条数赋值
							// this.courseInfo.records.push(res.data.data.records); // 将数据放入list中
							for(let i of res.data.data.records) {
								this.courseInfo.records.push(i);
							}
							this.loading = false;  // 下面的那个加载中显示   加载状态结束 
							// localStorage.setItem('courseInfo' , JSON.stringify(this.courseInfo));
						}
					});
				} else if(this.userInfo.roles[0] === 'STUDENT'){ // 学生
					await pageCourseForStudent(this.currentPage , this.maxPage).then(res => {
						console.log(res.data.data);
						if (res.data.data.records.length === 0) { // 判断获取数据条数若等于0
							this.finished = true; // 停止加载
							console.log('停止加载');
						} else {
							this.courseInfo.total = res.data.data.total; // 给数据条数赋值
							// this.courseInfo.records.push(res.data.data.records); // 将数据放入list中
							for(let i of res.data.data.records) {
								this.courseInfo.records.push(i);
							}
							this.loading = false;  // 下面的那个加载中显示   加载状态结束 
							// localStorage.setItem('courseInfo' , JSON.stringify(this.courseInfo));
						}
					});
				}
			},			
			goDetailBanke(c) { // 点击list进入班课详情页
				// localStorage.setItem('BKdetail' , JSON.stringify(c));
				
				localStorage.setItem('detailBankeInfo' , JSON.stringify(c));
				this.$router.push({
					name: 'detailBanke',
					// params: {
					// 	bkInfo: c
					// }
				});
			}	
		},
			
		
	}
</script>

<style>
</style>
